package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.SearchHistoryService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 陈辉
 * @data 2023 15:32
 */
@Service
public class SearchHistoryServiceImpl implements SearchHistoryService {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 加载app搜索历史记录
     *
     * @return
     */
    @Override
    public ResponseResult load() {
        //1. 拿到当前登录用户的id
        Integer userId = Integer.valueOf(ApUserThreadLocalUtil.getUser());

        if (userId == null || userId == 0)
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);

        //2. 根据当前登录用户的id来查询mongo中的ap_user_search表
        List<ApUserSearch> history = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime")),
                ApUserSearch.class);

        //3. 将查到的结果返回
        return ResponseResult.okResult(history);
    }

    /**
     * 删除历史记录
     *
     * @param map
     * @return
     */
    @Override
    public ResponseResult del(Map map) {
        //1. 拿到历史记录id
        Object historyId = map.get("id");
        if (historyId == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);

        //2. 删除对应的历史记录
        mongoTemplate.remove(Query.query(Criteria.where("id").is(historyId.toString())),ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存搜索记录
     *
     * @param searchWord
     */
    @Override
    public void save(String searchWord) {
        //1. 查询当前用户有没有针对本次的搜索词的搜索记录
        List<ApUserSearch> list = mongoTemplate.find(Query.query(Criteria.where("userId").is(Integer.valueOf(ApUserThreadLocalUtil.getUser())))
                .with(Sort.by(Sort.Direction.DESC,"createdTime")), ApUserSearch.class);

        if (list != null && list.size() > 0) {
            //2. 有： 将记录时间更新为当前系统时间即可
            for (ApUserSearch apUserSearch : list) {
                if (apUserSearch.getKeyword().equals(searchWord)) {
                    apUserSearch.setCreatedTime(new Date());
                    mongoTemplate.save(apUserSearch);
                    return;
                }
            }
            //3. 没有：判断当前用户搜索记录总量有没有超过10
            if (list.size() >= 10){
                //5. 超过10条：拿本次记录替换最旧的一条记录
                ApUserSearch oldestSearch = list.get(list.size() - 1);
                oldestSearch.setKeyword(searchWord);
                oldestSearch.setCreatedTime(new Date());
                mongoTemplate.save(oldestSearch);
            }

        }

        //4. 没有超过：直接保存历史记录
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setKeyword(searchWord);
        apUserSearch.setUserId(Integer.valueOf(ApUserThreadLocalUtil.getUser().toString()));
        apUserSearch.setCreatedTime(new Date());
        mongoTemplate.save(apUserSearch);
    }
}
